package com.jusda.service.update;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jusda.entity.UserInfo;
import com.jusda.entity.UserScore;
import com.jusda.entity.level.UserScoreLevelEnum;
import com.jusda.entity.template.UserScoreTemplate;
import com.jusda.mapper.UpdateMapper;
import com.jusda.mapper.UserScoreJpaResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.function.BiFunction;

/**
 * @Author yiyi
 * @Date 2022/2/14-上午11:43
 * @Description:
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UpdateServiceImpl implements UpdateService {

    private final UpdateMapper updateMapper;


    private final UserScoreJpaResp userScoreJpaResp;

    private final RestHighLevelClient restHighLevelClient;

    private static final IndexRequest user_score = new IndexRequest("user_score");

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public List<UserInfo> queryByUserIdList(List<Long> userIdList) {
        return updateMapper.queryByUserIdList(userIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserScore(UserScore o) {
        o.setScoreLevel(UserScoreLevelEnum.EXCELLENT);
        userScoreJpaResp.save(o);
        // 同步最新数据到es
        log.debug("同步一条最新数据到es...");
        SyncDataToEs(o);
    }

    /***
     * 注，es其实并不支持事务，方法发生异常时其实并不会回滚数据。
     * @param userScore
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void SyncDataToEs(UserScore userScore) {
        try {
            user_score.id(String.valueOf(userScore.getId()));
            UserScoreTemplate instance = UserScoreTemplate.getInstance(userScore.getId(), userScore.getUsername(), userScore.getScoreLevel());
            IndexRequest source = user_score.source(objectMapper.writeValueAsString(instance), XContentType.JSON);
            restHighLevelClient.index(source, RequestOptions.DEFAULT);
        } catch (JsonProcessingException e) {
            log.error("json转换失败,{}", e);
        } catch (IOException e) {
            log.error("Es写入数据失败,{}", e);
            e.printStackTrace();
        }
    }

    //    @Transactional(rollbackFor = Exception.class)
    public void set(UserScore userScore) throws IOException {
        userScore.setUsername("test");
        userScoreJpaResp.save(userScore);
    }

    public static void main(String[] args) {
//        Consumer<String>  consumer = System.out::println;
//        consumer.accept("hello world!");

//
//        Function<String,String> function = (value)->{
//            if (StringUtils.isBlank(value)){
//                throw new RuntimeException("参数错误!");
//            }
//           return value;
//        };
//        System.out.println(function.apply("12"));


        BiFunction<String,String,String> biFunction =(value,param)->{
            if (StringUtils.isBlank(value)){
                throw new RuntimeException("参数错误!错误的参数值:"+param);
            }
           return value;
        };

        System.out.println(biFunction.apply("", "id"));
    }

}
